<template>
<div>
  <div>
    <button @click="remove">关闭Rain</button>
    <button @click="open">开启Rain</button>
  </div>
  <div id="container">

  </div>
</div>
</template>

<script>
import L from "leaflet";
import 'leaflet-rain';
import "proj4leaflet";
import "leaflet/dist/leaflet.css";
import dataLineOne from "@/data/lineOne.js";
import dataLines from "@/data/lines.js";
import { points } from "@/data/points.js";
import {rain} from '@/data/rain'

import '@/data/leaflet-polygon.fillPattern'
export default {
  name: 'App',
  data(){
    return{
      map: null,
      labelGroup: null, //文本图层
      markerLayer: null, //marker 图层
      levelCode: '',
      pointLayer: null,
      migrationLayer: null,
      searchData: null,
      datas: null,
      parentId: '',
      pointList: [],
      centerStation: [],
      stationList: [],
      type: '1',
      treeStation: [],
    }
  },
  mounted(){

    this.$nextTick(() => {
      setTimeout(() => {
        this.initMap();
      }, 100);
    })
  },
  methods: {
    initMap(){
      const crs = new L.Proj.CRS(
          "EPSG:3395",
          "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs",
          {
            resolutions: (function () {
              const level = 20;
              const res = [];
              res[0] = Math.pow(2, 18);
              for (let i = 1; i < level; i++) {
                res[i] = Math.pow(2, 18 - i);
              }
              console.log(res)
              return res;
            })(),

            origin: [0, 0],  // 地图坐标原点
            bounds: L.bounds([20037508.342789244, 0], [0, 20037508.342789244]),
          }
      );
      const center = [23.1791, 113.4644];
      // const center =  [48, 10];
      var osm = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
            maxZoom: 10,
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
          })
        console.log(L.CRS)
      this.map = L.map("container", {
        // crs: L.CRS.EPSG3395,
        // crs: L.CRS.EPSG3857,
        // crs: L.CRS.EPSG4326,
        // crs: L.CRS.EPSG900913,
          crs,
        layers: [osm],
        center,
        zoom: 10,
        // maxZoom: 10,
        // minZoom: 10,
        // zoomControl: false,
        // attributionControl: false,
        // preferCanvas: true,
      });
      console.log(this.map,'map')
      if (this.map) {
        this.labelGroup = new L.layerGroup(); //文本图层
        this.labelGroup.addTo(this.map);
        this.markerLayer = new L.layerGroup(); //标记
        this.markerLayer.addTo(this.map);
        this.map.doubleClickZoom.disable();
        this.map.touchZoom.enable();

        this.addBoundary() // 添加边界线
        this.addBorderLineText() // 區域添加文字
        this.addRain() // 下雨效果

      } else {
        console.error("--地图加载失败!!!--");
      }
    },
    // 添加边界线
    addBoundary() {
      let geojson = {
        type: "FeatureCollection",
        features: [],
      };

      let _geojson = JSON.parse(JSON.stringify(geojson));

      for (let item of dataLines.boundaries) {
        geojson.features.push({
          type: "Feature",
          geometry: {
            type: "Polygon",
            coordinates: [
              item.split(";").map((ii) => {
                const lng = Number(ii.split(",")[0]);
                const lat = Number(ii.split(",")[1]);
                return [lng, lat];
              }),
            ],
          },
        });
      }
      for (let item of dataLineOne.boundaries) {
        _geojson.features.push({
          type: "Feature",
          geometry: {
            type: "Polygon",
            coordinates: item.map((i) => {
              return i.split(";").map((ii) => {
                const lng = Number(ii.split(",")[0]);
                const lat = Number(ii.split(",")[1]);
                return [lng, lat];
              });
            }),
          },
        });
      }

      const onEachFeature = (feature, layer) => {
        if (feature.properties) {
        }
      };

      const styleFunc = (weight) => {
        return {
          stroke: true, // 边界线
          color: "#218ef3", // 边界线颜色
          weight: weight, // 边界线权重
          opacity: 1, // 边界线透明度

          fill: true, // 填充
          fillColor: "#c0def6", // 填充色
          fillOpacity: 0.3, // 填充透明度
        };
      };

      const vectorCity = L.geoJSON(geojson, {
        onEachFeature,
        style: styleFunc(2),
      });

      const vectorDistrict = L.geoJSON(_geojson, {
        onEachFeature,
        style: styleFunc(1),
      });

      vectorCity.addTo(this.map);
      vectorDistrict.addTo(this.map);
    },

    // 加文字标注
    addBorderLineText() {
      const textList = [
        { lon: "113.22765200", lat: "23.09343500", text: "荔湾区" },
        { lon: "113.28093400", lat: "23.13450200", text: "越秀区" },
        { lon: "113.32378000", lat: "23.08267000", text: "海珠区" },
        { lon: "113.37679100", lat: "23.15899700", text: "天河区" },
        { lon: "113.26375900", lat: "23.32304800", text: "白云区" },
        { lon: "113.48057200", lat: "23.10657500", text: "黄埔区" },
        { lon: "113.42796800", lat: "22.98000000", text: "番禺区" },
        { lon: "113.21594600", lat: "23.43880700", text: "花都区" },
        { lon: "113.59021600", lat: "22.71908100", text: "南沙区" },
        { lon: "113.70992900", lat: "23.33455400", text: "增城区" },
        { lon: "113.63494500", lat: "23.61352300", text: "从化区" },
      ];

      textList.map((i) => {
        const myIcon = L.divIcon({
          html: i.text,
          className: "my-div-icon",
          iconSize: [60, 20],
        });
        L.marker([Number(i.lat), Number(i.lon)], {
          icon: myIcon,
        }).addTo(this.map);
      });
    },


    // 添加下雨效果
    addRain() {
      var glsl = require('glslify');

      var vertexShader = glsl(["#define GLSLIFY 1\nuniform mat4 u_matrix;\nattribute vec2 a_position;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);\n    gl_PointSize = 10.0;\n}\n"]);
      var fragmentShader = glsl(["precision mediump float;\n#define GLSLIFY 1\nuniform vec2 u_resolution;\nuniform float u_angle;\nuniform float u_width;\nuniform float u_spacing;\nuniform float u_length;\nuniform float u_interval;\nuniform float u_speed;\nuniform float u_time;\nuniform int u_color;\n\nfloat drawCoord(float coord, float fill, float gap) {\n    float patternLength = fill + gap;\n    float modulo = mod(coord, patternLength);\n\n    return step(modulo, patternLength - gap);\n}\n\nvec3 getColor(int color) {\n    float red = float(color / 256 / 256);\n    float green = float(color / 256 - int(red * 256.0));\n    float blue = float(color - int(red * 256.0 * 256.0) - int(green * 256.0));\n\n    return vec3(red / 255.0, green / 255.0, blue / 255.0);\n}\n\nvoid main() {\n    mat2 rotationMatrix = mat2(\n        cos(u_angle), -sin(u_angle),\n        sin(u_angle), cos(u_angle)\n    );\n\n    vec2 rotatedFragCoord = rotationMatrix * gl_FragCoord.xy;\n\n    float yShift = u_time * u_speed;\n    float drawX = drawCoord(rotatedFragCoord.x, u_width, u_spacing);\n    float drawY = drawCoord(rotatedFragCoord.y + yShift, u_length, u_interval);\n\n    float draw = drawX * drawY;\n\n    if (!bool(draw)) discard;\n\n    vec3 color = getColor(u_color);\n\n    gl_FragColor = vec4(color, 1.0);\n}\n"]);
      // 下雨options參數
      let options = {
        angle: 80,
        width: 1,
        spacing: 10,
        length: 4,
        interval: 10,
        speed: 1,
        color: '',
        vertexShader: vertexShader,
        fragmentShader: fragmentShader
      }
      // const newAry = dataLineOne.boundaries.concat(dataLines.boundaries)
      // // 遍历切割成经纬度
      // let  lastAry
      // newAry.flat().forEach(coordinate => {
      //   lastAry = coordinate.split(";").map((ii) => {
      //     const lng = Number(ii.split(",")[0]);
      //     const lat = Number(ii.split(",")[1]);
      //     return [lat,lng];
      //   });
      //
      // });
      var newArray = rain.map(function(subArray) {
        return subArray.map(function(innerArray) {
          // 交换位置
          return [innerArray[1], innerArray[0]];
        });
      });
      console.log(newArray,'newary')
      L.rain(newArray ,options).addTo(this.map)
    },
    remove(){
      // L.rain().stop()
      const element = document.getElementsByClassName("webgl-canvas")[0];
      // console.log( document.getElementsByClassName("webgl-canvas"))
      element.style.display="none";
      // this.map.removeLayer(L.rain)
    },
    // 開啟
    open(){
      const element = document.getElementsByClassName("webgl-canvas")[0];
      // console.log( document.getElementsByClassName("webgl-canvas"))
      element.style.display="block";
    }
  },

}
</script>

<style>
#container {
  width: 100vw;
  height: 100vh;
  top: 113px;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 10px;
  overflow: hidden;
  outline: none;
  position: absolute;
  z-index: 0;
  background-color: transparent
}
.webgl-canvas{
  //display: none;
}
</style>
